package com.jcl.recruit.console.user.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jcl.core.common.page.PageResult;
import com.jcl.core.constants.Constant;
import com.jcl.recruit.console.user.logic.ConsoleUserLogic;
import com.jcl.recruit.console.user.model.SysUser;
import com.jcl.recruit.console.user.model.vo.SysUserVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

import static org.springframework.beans.support.PagedListHolder.DEFAULT_PAGE_SIZE;

/**
 * @ClassName UserService
 * @Author yyliu
 * @Date 2018/12/18 16:39
 * @Version 1.0
 **/
@Service
public class ConsoleUserService {

    @Autowired
    private ConsoleUserLogic consoleUserLogic;

    public PageResult pageList(Integer curPage, Integer rowSize) {
        curPage = null == curPage ? 1 : rowSize;
        rowSize = null == rowSize ? DEFAULT_PAGE_SIZE : rowSize;
        PageHelper.startPage(curPage, rowSize);
        List<SysUser> userList = consoleUserLogic.findList();
        PageInfo info = new PageInfo(userList);
        List<SysUserVo> voList = consoleUserLogic.constractUserList(info.getList());
        return new PageResult(Integer.valueOf(curPage), rowSize,
                info.getTotal(), voList);
    }

    public SysUserVo findOne(Integer id) {

        SysUser user = consoleUserLogic.findOneById(id);
        if(null == user){
           return null;
        }
        return consoleUserLogic.constractUser(user);
    }

    public int updateUser(SysUserVo userVo) {
        SysUser user = null;
        if (null != userVo.getId()) { // update
            user = consoleUserLogic.findOneById(userVo.getId());
        }
        if (null != userVo.getId() && null == user) {
            // 请求用户不存在
            return 2;
        } else {
            user = new SysUser();
        }
        BeanUtils.copyProperties(userVo, user);
        if (null != userVo.getId()) { // update
            user.setUpdateTime(new Date());
            consoleUserLogic.update(user);
        } else {
            user.setCreateTime(new Date());
            user.setUpdateTime(new Date());
            user.setStatus(Constant.NUMBER_0);
            consoleUserLogic.insert(user);
        }

        return 1;
    }

    public int deleteUser(Integer id) {

        return consoleUserLogic.delete(id);
    }

}
